#import "SiteController.h"
#import "Settings.h"

@interface SiteController ()<SettingsListener, UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) Settings* settings;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *rightBarButtonItem;
@property (nonatomic) BOOL isFirstTime;
@end

@implementation SiteController

@synthesize webView;
@synthesize settings = _settings;
@synthesize isFirstTime;
@synthesize rightBarButtonItem;

-(void)login {
    NSURL *aUrl = [NSURL URLWithString:[self.settings.url stringByAppendingString:@"/Login"]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl];
    [request setHTTPMethod:@"POST"];
    NSString *postString = [NSString stringWithFormat:@"usernamelogin=%@&passwordlogin=%@", self.settings.username, self.settings.password];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    [self.webView loadRequest:request];
}

- (IBAction)startTapped:(id)sender {
    [self login];
}

-(void)viewDidLoad {
    [super viewDidLoad];
    self.isFirstTime = YES;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.isFirstTime) {
        [self login];
        self.isFirstTime = NO;
    }
}

-(void)setSettings:(Settings *)settings {
    _settings = settings;
    [settings subscribeToChanges:self];
    [self login];
}

-(BOOL)settingsChanged:(Settings *)settings error:(NSError **)error {
    [self login];
    return YES;
}

-(void)webViewDidStartLoad:(UIWebView *)webView {
    UIActivityIndicatorView* spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [spinner startAnimating];
    self.rightBarButtonItem.customView = spinner;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    id spinner = self.rightBarButtonItem.customView;
    if ([spinner isKindOfClass:[UIActivityIndicatorView class]]) {
        [spinner stopAnimating];
    }
    self.rightBarButtonItem.customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
}

@end
